package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.TreeMap;

public class BookLibrary implements Library {
    private TreeMap<String, Book> availableList = new TreeMap<String, Book>();
    private TreeMap<String, Book> checkedOutList = new TreeMap<String, Book>();
    private BufferedReader reader;

    public BookLibrary(BufferedReader reader) {
        initLibrary();
        this.reader = reader;
    }

    @Override
    public void initLibrary() {
        Book book1 = new Book("title1", "author1", "year1");
        Book book2 = new Book("title2", "author2", "year2");
        Book book3 = new Book("title3", "author3", "year3");
        availableList.put("1", book1);
        availableList.put("2", book2);
        availableList.put("3", book3);
    }

    @Override
    public String display() {
        System.out.println("The available books are: ");
        String result = "";
        for (String id : availableList.keySet()) {
            Book book = availableList.get(id);
            result += id + "---" + book.title + "---" + book.author + "---" + book.year + "\n";
        }
        System.out.println(result);
        return result;
    }

    @Override
    public boolean checkout() throws IOException {
        System.out.println("Please input the book id you want to checkout: ");
        String bookId = reader.readLine();
        if (availableList.keySet().contains(bookId)) {
            checkedOutList.put(bookId, availableList.get(bookId));
            availableList.remove(bookId);
            System.out.println("Thank you! Enjoy the book.\n");
            return true;
        }
        System.out.println("That book is not available.\n");
        return false;
    }

    public TreeMap<String, Book> availableList() {
        return availableList;
    }


    public TreeMap<String, Book> checkedOutList() {
        return checkedOutList;
    }

    @Override
    public boolean returnItem() throws IOException {
        System.out.println("Please input the book id you want to return: \n");
        String bookId = reader.readLine();
        if (checkedOutList.keySet().contains(bookId)) {
            availableList.put(bookId, checkedOutList.get(bookId));
            checkedOutList.remove(bookId);
            System.out.println("Thank you for returning the book.\n");
            return true;
        }
        System.out.println("That is not a valid book to return.\n");
        return false;
    }
}
